<template>
	<view>
		<wd-message-box />
		<wd-toast />
		<wd-search v-model="searchValue" @search="handlesearch" hide-cancel placeholder-left placeholder="请输入关键字">
			<template #prefix>
				<wd-popover mode="menu" :content="menu" @menuclick="changeSearchType">
					<view class="search-type">
						<text>{{ searchType }}</text>
						<wd-icon custom-class="icon-arrow" name="fill-arrow-down"></wd-icon>
					</view>
				</wd-popover>
			</template>
		</wd-search>


		<wd-tabs v-model="activeTab" auto-line-width @change="handleTabChange">
			<wd-tab v-for="tab in tabs" :key="tab.value" :title="tab.label" :name="tab.value">
				<view class="px-1 py-1">
					<wd-table :data="list[tab.value]" :height="600" :border="false" @row-click="handleClick"
						v-if="list[tab.value]">
						<wd-table-col v-for="(col, index) in columns[tab.value]" :key="index" :prop="col.prop"
							:label="col.label" :width="col.width || '100'" :align="col.align || 'center'">
							<template #value="{ row }">
								<template v-if="col.prop.includes('.')">
									<!-- 如果是嵌套属性，拆分路径并按路径访问数据 -->
									{{ getNestedValue(row, col.prop) || '-' }}
								</template>
								<template v-else-if="col.isTag">
									<wd-tag custom-class="space"
										:type="col.color ? col.color(row[col.prop]) : 'primary'">
										{{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-') }}
									</wd-tag>
								</template>
								<template v-else>
									{{ col.format ? (col.format(row[col.prop]) || '-') : (row[col.prop] || '-') }}
								</template>
							</template>
						</wd-table-col>
						<wd-table-col prop="grade" label="操作" width="200" fixed align="left"
							v-if="tab.value === 'currentList'">
							<template #value="{ row }">
								<text class="px-1 text-#4d80f0" @click.stop="handleProcessDetail(row)">
									查看
								</text>
								<text class="px-1 text-#4d80f0"
									@click.stop="row.status === 3  ? handleAddOrEdit(row.id, true) : handleAddOrEdit(row.id)">
									{{ row.status === 0 ? '修改' :  row.status === 3 ? '重新填写' : ''
									}}
								</text>
								<text class="px-1 text-#4d80f0" @click.stop="handleDelete(row.id)">
									{{ row.status === 0 ? '取消' : '' }}
								</text>
								<text class="px-1 text-#4d80f0" @click.stop="handleExpedite(row)">
									{{ row.status !== 2 && row.status !== 4 ? '催办' : '' }}
								</text>
							</template>
						</wd-table-col>
					</wd-table>
				</view>
			</wd-tab>
		</wd-tabs>

		<!-- 分页组件 -->
		<Pagination :total="total" :pageNo="queryParams.pageNo" :pageSize="queryParams.pageSize"
			@update:pageNo="changePage" />
		<view class="mx-12 my-8 ">
			<up-button text="新增" color="#5ac725" shape="circle" @click="handleAddOrEdit()"
				v-if="activeTab === `currentList`"></up-button>
		</view>


	</view>
</template>

<script setup lang="ts">
import { onShow } from '@dcloudio/uni-app'
import { ref, onMounted, watch, nextTick } from 'vue'
import * as LeaveApi from '@/api/bpm/leave'
import { AnnualLeaveBalanceApi } from '@/api/Hr/annualLeaveBalance'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import * as UserApi from '@/api/system/user'
import { DICT_TYPE, getIntDictOptions, getDictLabel, getDictColor } from '@/utils/dict'
import Pagination from '@/components/pagination/index.vue'
import { useMessage, useToast } from 'wot-design-uni'
import { expediting } from '@/utils/processinstance'
import { formatDate } from '@/utils/formatTime'


const message = useMessage()
const toast = useToast()

const userOptions = ref<any>([])

//存储数据
const list = ref<any>({
	currentList: [],  // 集团起诉案件审批
	historyList: [],   // 集团应诉案件审批
})
// 表单列配置项
const columns = {
	currentList: [
		{ prop: 'reason', label: '请假原因', },
		{
			prop: 'type',
			label: '请假类型',
			format: (val: any) => getDictLabel(DICT_TYPE.BPM_OA_LEAVE_TYPE, val),
			color: (val: any) => getDictColor(DICT_TYPE.BPM_TASK_STATUS, val),
			isTag: true
		},
		// { prop: 'submitter', label: '资料提交人', width: 120 },
		// { prop: 'submitterPhone', label: '联系电话', width: 120 },
		// { prop: 'caseReason', label: '案由', width: 120 },
		// { prop: 'amountInvolved', label: '涉案标的', width: 120 },
		// { prop: 'defendant', label: '被起诉人', width: 120 },
		{
			prop: 'status',
			label: '审批状态',
			align: 'center',
			width: 100,
			format: (val: any) => getDictLabel(DICT_TYPE.BPM_TASK_STATUS, val),
			color: (val: any) => getDictColor(DICT_TYPE.BPM_TASK_STATUS, val),
			isTag: true
		}

	],
	historyList: [
		{ prop: 'employeeName', label: '员工姓名', },
		{ prop: 'departmentName', label: '所在部门', },
		{ prop: 'serviceYears', label: '工龄', width: 60 },
		{ prop: 'totalAnnualLeave', label: '年假天数', width: 80 },
		// { prop: 'usedLeaveDays', label: '已使用假期天数', },
		{ prop: 'remainingLeaveDays', label: '假期余额', width: 80 },
		// { prop: 'submitter', label: '资料提交人', width: 160 },
		// { prop: 'submitterContact', label: '联系电话', width: 160 },
		// { prop: 'caseReason', label: '案由', width: 160 },
		// {
		// 	prop: 'status',
		// 	label: '审批状态',
		// 	align: 'center',
		// 	width: 110,
		// 	format: (val: any) => getDictLabel(DICT_TYPE.BPM_TASK_STATUS, val),
		// 	color: (val: any) => getDictColor(DICT_TYPE.BPM_TASK_STATUS, val),
		// 	isTag: true
		// }

	]

} as any
const activeTab = ref('currentList')
const tabs = ref([
	{
		label: '请销假',
		value: 'currentList',
		api: LeaveApi.getLeavePage,
	},
	{
		label: '年销假余额',
		value: 'historyList',
		api: AnnualLeaveBalanceApi.getAnnualLeaveBalancePage,
	}
])
const queryParams = ref<any>({
	pageNo: 1,
	pageSize: 10,
	title: undefined,
	reason: undefined,
	employeeName: undefined,
})
const total = ref(0)
const loading = ref(false)

const userList = ref<any[]>([])
const searchType = ref<string>('原因')
const searchValue = ref<string>('')
const menu = ref<any[]>([
	{
		content: '原因',
		prop: 'reason'
	},
	{
		content: '员工姓名',
		prop: 'employeeName'
	}
])
const handleTabChange = async (value: any) => {
	console.log('value', value);

	searchValue.value = ''
	queryParams.value.reason = undefined;
	queryParams.value.employeeName = undefined;
	// await nextTick();
	fetchList(value.name);
	console.log('activeTab', activeTab.value);
	console.log('columns', columns);
	console.log('list', list.value);

}
function changeSearchType({ item }: { item: any }) {
	searchType.value = item?.content
}

const handlesearch = () => {
	// 找到选中的搜索字段
	const selectedMenu = menu.value.find(item => item.content === searchType.value);
	if (selectedMenu) {
		// 清空之前的搜索条件
		queryParams.value.reason = undefined;
		queryParams.value.employeeName = undefined;
		// 根据选中的搜索类型设置搜索值
		if (activeTab.value === 'currentList') {
			queryParams.value.reason = searchValue.value.trim()
		} else {
			queryParams.value.employeeName = searchValue.value.trim()
		}
		// queryParams.value[selectedMenu.prop] = value.value.trim();
		// 重新获取数据
		fetchList();
	}
};
// 切换分页
const changePage = (newPage: any) => {
	queryParams.value.pageNo = newPage
	fetchList()
}
function handleSubmit() {
	fetchList()
}

// 获取列表
const fetchList = async (tabValue?: string) => {
	const currentTabValue = tabValue || activeTab.value
	const currentTab = tabs.value.find(t => t.value === currentTabValue)
	if (!currentTab) return

	loading.value = true
	try {
		const response = await currentTab.api(queryParams.value)

		// 保证 list 一定是数组
		const rawList = Array.isArray(response.list) ? response.list : []

		// 格式化数据，保证结构一致
		const normalizedList = rawList.map((item: any) => {
			return {
				...item,
				status: item?.isApproved
					? 0
					: (item?.status ?? null) // 👈 如果没有 status，填 null
			}
		})

		list.value[currentTabValue] = normalizedList
		total.value = response.total || 0
	} catch (error) {
		console.error(error)
		list.value[currentTabValue] = [] // 👈 出错兜底
	} finally {
		loading.value = false
	}
}
/** 审批进度 */
const handleProcessDetail = (row: any) => {
	const url = `/pagesPackage/OAsystemAutomation/bpm/oa/leave/detail?processInstanceId=${row.processInstanceId}&id=${row.id}`;
	uni.navigateTo({
		url: url
	});
}
/** 点击一整行跳转至详情页面 */
const handleClick = ({ rowIndex }: any) => {
	console.log('rowIndex',rowIndex);
	
	handleProcessDetail(list.value[rowIndex])

}
/** 新增页面 */
const handleAddOrEdit = (id?: any, resubmit = false) => {
	let url = `/pagesPackage/OAsystemAutomation/bpm/oa/leave/create`; // 默认新增页面
	// 如果 id 存在，拼接 id 作为参数
	if (id) {
		if (resubmit === true) {
			console.log('resubmit', resubmit);
			url += `?id=${id}&resubmit=1`;
		}
		console.log('传过来的Id', id);
		url += `?id=${id}&resubmit=0`;
	} else {
		url += `?resubmit=0`;
	}
	uni.navigateTo({ url });
}
const value1 = ref('')
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
	try {
		// 删除的二次确认
		await message.prompt({
			// msg: '请输入取消原因',
			title: '请输入取消原因',  // 添加标题
			inputValue: '',
		})
			.then(async (val) => {
				console.log('val', val);

				// 发起删除
				await ProcessInstanceApi.cancelProcessInstanceByStartUser(id, val.value as any)
				// 显示成功提示
				toast.success('取消成功')
				// 刷新列表
				await fetchList()
			})
			.catch((error) => {
				console.log(error)
			})

	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
/** 获取用户列表 */
const getUserList = async () => {
	try {
		userList.value = await UserApi.getSimpleUserList();
	} catch (error) {
		console.error("获取用户列表失败:", error);
		userOptions.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
}
const handleExpedite = (row: any) => {
	expediting({
		processInstanceId: row.processInstanceId,
		processName: '青运-智能人事-请销假'
	})
}
// 生命周期
onMounted(() => {
	fetchList()
	getUserList()
})
onShow(() => {
	fetchList()
})
</script>

<style scoped lang="scss">
.container {
	padding: 20px 10px;
}

.search-type {
	position: relative;
	height: 30px;
	line-height: 30px;
	padding: 0 8px 0 16px;
}

.search-type::after {
	position: absolute;
	content: '';
	width: 1px;
	right: 0;
	top: 5px;
	bottom: 5px;
	background: rgba(0, 0, 0, 0.25);
}

.search-type {
	:deep(.icon-arrow) {
		display: inline-block;
		font-size: 20px;
		vertical-align: middle;
	}
}
</style>